package com.wwz.leetcode;

import org.junit.Test;

/**
 * 给你一个字符串 s，找到 s 中最长的回文子串。
 */
public class LeetCode5 {
    @Test
    public void test() {
        String s = "ccc";
        //String s = "acbcb";
        System.out.println(longestPalindrome(s));
    }

    public String longestPalindrome(String s) {
        int len = s.length();
        if (len < 2) {
            return s;
        }
        int maxLength = 0;
        int left = 0;
        int right = 0;
        for (int i = 0; i < len - 1; i++) {
            for (int j = i + 1; j < len; j++) {
                // 长度比已知要长 而且 是回文串
                if ((maxLength < j - i) && validateString(i, j, s)) {
                    left = i;
                    right = j;
                    maxLength = j - i;
                }
            }
        }
        return s.substring(left, right + 1);
    }

    // 是否为回文串
    public boolean validateString(int left, int right, String s) {
        while (left <= right) {
            if (s.charAt(left) == s.charAt(right)) {
                left++;
                right--;
            } else {
                return false;
            }
        }
        return true;
    }
}
